package cn.gzjp.modules.logis.web.api.web;

import cn.gzjp.common.config.ConfigUtils;
import cn.gzjp.common.utils.pay.PayUtils;
import cn.gzjp.common.utils.pay.XmlUtils;
import cn.gzjp.common.web.BaseController;
import cn.gzjp.modules.gas.entity.GasOrder;
import cn.gzjp.modules.gas.entity.GasRecharge;
import cn.gzjp.modules.gas.service.GasOrderService;
import cn.gzjp.modules.gas.service.GasRechargeService;
import cn.gzjp.modules.it.api.bean.CommonJson;
import cn.gzjp.modules.logis.entity.LogisDelivery;
import cn.gzjp.modules.logis.entity.LogisDeliveryLog;
import cn.gzjp.modules.logis.entity.LogisInsurePhoto;
import cn.gzjp.modules.logis.entity.LogisUser;
import cn.gzjp.modules.logis.service.LogisDeliveryService;
import cn.gzjp.modules.logis.service.LogisInsurePhotoService;
import cn.gzjp.modules.logis.service.LogisUserService;
import cn.gzjp.modules.rice.entity.RiceOrder;
import cn.gzjp.modules.rice.service.RiceOrderService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 微信支付通知
 *
 * @author zengcp
 */
@Controller
@RequestMapping(value = "${frontPath}/wxPayback")
public class WxMinPayBackController extends BaseController {

    public static Logger payLog = LoggerFactory.getLogger("payLog");

    @Autowired
    private LogisDeliveryService logisDeliveryService;

    @Autowired
    private LogisUserService logisUserService;
    @Autowired
    private RiceOrderService riceOrderService;

    @RequestMapping(value = "notify/{type}/{id}")
    @ResponseBody
    public String notify(@PathVariable(value = "type") String type, @PathVariable(value = "id") String orderId,
                         HttpServletRequest request) {
        payLog.info("微信支付成功回调方法 type=" + type + "|orderId=" + orderId);

        String result = null;
        try {
            List<String> lines = IOUtils.readLines(request.getInputStream());
            StringBuilder sb = new StringBuilder();
            for (String line : lines) {
                sb.append(line);
            }
            Map<String, String> params = XmlUtils.xmlToMap(sb.toString());

            String key = ConfigUtils.getProperty("mchKey3");

            boolean flag = PayUtils.checkSign(params, key);

            if (flag) {
                result = PayUtils.returnXml(true, null);
                String returnCode = params.get("return_code");
                String resultCode = params.get("result_code");


                if ("1".equals(type)) {
                    payLog.info("--更新运单订金支付情况");
                    LogisDelivery delivery = this.logisDeliveryService.get(orderId);
                    if ("SUCCESS".equals(returnCode)
                            && "SUCCESS".equals(resultCode)) {
                        String outTradeNo = params.get("out_trade_no");//商户订单号
                        String totalfee = params.get("total_fee");
                        String transactionId = params.get("transaction_id");
                        String openid = params.get("openid");
                        if (StringUtils.isNotBlank(transactionId)) {
                            delivery.setWxOrderId(transactionId);
                            delivery.setPayDate1(new Date());
                            delivery.setPayStatus("1");//已支付
                            delivery.setPayOpenId1(openid);
                            LogisUser logisUser = logisUserService.get(openid);
                            delivery.setReceiver(logisUser.getUnionId());
                            delivery.setRecOpenid(openid);//设置收货人
                            logisDeliveryService.save(delivery);
                            payLog.info("--设置收货人openid=" + openid + ",unionId="+logisUser.getUnionId());
                            payLog.info("--运单订单号：" + outTradeNo + ",微信订单号："
                                    + transactionId + " ,金额为：" + totalfee + "回调成功！");
                        }
                    } else {
                        payLog.info("--本地订单为：" + orderId + "回调时候，表明该订单支付失败！");

                    }
                }
                if ("2".equals(type)) {
                    payLog.info("--更新运单尾款支付情况");
                    LogisDelivery order = this.logisDeliveryService.get(orderId);
                    if ("SUCCESS".equals(returnCode)
                            && "SUCCESS".equals(resultCode)) {
                        String outTradeNo = params.get("out_trade_no");
                        String totalfee = params.get("total_fee");
                        String transactionId = params.get("transaction_id");
                        String openid = params.get("openid");
                        if (StringUtils.isNotBlank(transactionId)) {
                            order.setWxOrderId2(transactionId);
                            order.setPayDate2(new Date());
                            order.setPayStatus("2");//已支付尾款
                            order.setPayOpenId2(openid);
                            this.logisDeliveryService.save(order);
                            payLog.info("--运单订单号：" + outTradeNo + ",微信订单号："
                                    + transactionId + " ,金额为：" + totalfee + "回调成功！");
                        }
                    } else {
                        payLog.info("--本地订单为：" + orderId + "回调时候，表明该订单支付失败！");

                    }
                }

            } else {
                payLog.info("--本地订单为：" + orderId + "签名认证失败，可能存在攻击！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    @RequestMapping(value = "riceNotify/{id}")
    @ResponseBody
    public String riceNotify(@PathVariable(value = "id") String orderId,
                         HttpServletRequest request) {
        payLog.info("五常大米微信支付成功回调方法 |orderId=" + orderId);

        String result = null;
        try {
            List<String> lines = IOUtils.readLines(request.getInputStream());
            StringBuilder sb = new StringBuilder();
            for (String line : lines) {
                sb.append(line);
            }
            Map<String, String> params = XmlUtils.xmlToMap(sb.toString());

            String key = ConfigUtils.getProperty("mchKey3");

            boolean flag = PayUtils.checkSign(params, key);

            if (flag) {
                result = PayUtils.returnXml(true, null);
                String returnCode = params.get("return_code");
                String resultCode = params.get("result_code");

                RiceOrder order = this.riceOrderService.get(orderId);
                if ("SUCCESS".equals(returnCode)
                        && "SUCCESS".equals(resultCode)) {
                    String outTradeNo = params.get("out_trade_no");//商户订单号
                    String totalfee = params.get("total_fee");
                    String transactionId = params.get("transaction_id");
                    if (StringUtils.isNotBlank(transactionId)) {
                        order.setWxOrderId(transactionId);
                        order.setWxPayNotifyTime(new Date());
                        order.setBuyState(1);//已支付
                        riceOrderService.save(order);
                        payLog.info("--运单订单号：" + outTradeNo + ",微信订单号："
                                + transactionId + " ,金额为：" + totalfee + "回调成功！");
                    }
                } else {
                    payLog.info("--本地订单为：" + orderId + "回调时候，表明该订单支付失败！");

                }


            } else {
                payLog.info("--本地订单为：" + orderId + "签名认证失败，可能存在攻击！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}



